﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.Organization
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2017.03.04
    /// 描 述：角色管理
    /// </summary>
    public class RoleService
    {
        #region 仓储
        Repository<RoleEntity> _roleRepository => new Repository<RoleEntity>();
        #endregion
        #region 构造函数和属性
        private string fieldSql;
        public RoleService()
        {
            fieldSql = @"
                    t.F_RoleId,
                    t.F_Category,
                    t.F_EnCode,
                    t.F_FullName,
                    t.F_SortCode,
                    t.F_DeleteMark,
                    t.F_EnabledMark,
                    t.F_Description,
                    t.F_CreateDate,
                    t.F_CreateUserId,
                    t.F_CreateUserName,
                    t.F_ModifyDate,
                    t.F_ModifyUserId,
                    t.F_ModifyUserName
                    ";
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取角色数据列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<RoleEntity> GetList(string ProjectId)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_Base_Role t WHERE t.F_EnabledMark = 1 AND t.F_DeleteMark = 0 ");
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!string.IsNullOrEmpty(ProjectId))
                {
                    dp.Add(new SugarParameter("ProjectId", ProjectId, DbType.String));
                    strSql.Append(" AND  t.ProjectId = @ProjectId ");
                }
                else
                {
                    strSql.Append(" AND IFNULL(t.ProjectId,'')=''");
                }
                strSql.Append(" ORDER BY t.F_FullName");
                //return this.BaseRepository().FindList<RoleEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<RoleEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        public IEnumerable<RoleEntity> GetPageList(Pagination pagination, string queryJson)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(@",(SELECT GROUP_CONCAT(st1.F_RealName) FROM lr_base_user st1 
												LEFT JOIN lr_base_userrelation st2 on 	st1.F_UserId = st2.F_UserId		
												WHERE FIND_IN_SET(st2.F_ObjectId,t.F_RoleId)) AS MemberName");
                strSql.Append(" FROM LR_Base_Role t ");
                strSql.Append("  WHERE t.F_EnabledMark = 1 AND t.F_DeleteMark = 0 ");

                var queryParam = queryJson.ToJObject();
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["ProjectId"].IsEmpty())
                {
                    dp.Add(new SugarParameter("ProjectId", queryParam["ProjectId"].ToString(), DbType.String));
                    strSql.Append("AND  t.ProjectId = @ProjectId ");
                }
                else
                {
                    strSql.Append("AND IFNULL(t.ProjectId,'')=''");
                }
                if (!queryParam["keyword"].IsEmpty())
                {
                    dp.Add(new SugarParameter("keyword", "%" + queryParam["keyword"].ToString() + "%", DbType.String));
                    strSql.Append(" AND( t.F_FullName like @keyword or t.F_EnCode like @keyword ) ");
                }

                //return this.BaseRepository().FindList<RoleEntity>(strSql.ToString(),dp, pagination);
                return SqlSugarHelper.Db.SqlQueryable<RoleEntity>(strSql.ToString()).AddParameters(dp).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取角色数据列表
        /// </summary>
        /// <param name="roleIds">主键串</param>
        /// <returns></returns>
        public IEnumerable<RoleEntity> GetListByRoleIds(string roleIds)
        {
            try
            {
                return _roleRepository.GetList(t => roleIds.Contains(t.F_RoleId));
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取实体数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public RoleEntity GetEntity(string keyValue)
        {
            try
            {
                return _roleRepository.GetById(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 虚拟删除角色
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void VirtualDelete(string keyValue)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                RoleEntity entity = new RoleEntity()
                {
                    F_RoleId = keyValue,
                    F_DeleteMark = 1
                };
                _roleRepository.Update(entity);
                SqlSugarHelper.Db.Ado.ExecuteCommand(" Delete  From LR_BASE_USERRELATION where F_OBJECTID = @keyValue  ", new { keyValue = keyValue });

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 保存角色（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="roleEntity">角色实体</param>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ref RoleEntity roleEntity)
        {
            try
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    roleEntity.Modify(keyValue);
                    _roleRepository.Update(roleEntity);
                }
                else
                {
                    roleEntity.Create();
                    _roleRepository.Insert(roleEntity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }

        } 
        #endregion
    }
}
